const Pzip = require('pizzip')
const Docxtemplate = require('docxtemplater')
const fs = require('fs')
// const context = fs.readFileSync('./input/4.3.docx', 'binary')
const context = fs.readFileSync('./input/15.2实体合稿.docx', 'binary')
const { getJSONoneSheet, getJSON } = require('./pasreJSON.JS')
const expressionParser = require('docxtemplater/expressions.js')
// const getArrayJOSN = require('./createJson.js')
const array = require("./output/array.json")
const data = require("./input/data.json")
const zip = new Pzip(context)
const doc = new Docxtemplate(zip, {
  parser: expressionParser,
  linebreaks: true,
})

/**
 * 随机生成字符串
 * @returns string
 */
function generateRandomString() {  
    const firstThreeLetters = generateRandomStringNoNumber()
    const separator = '-';  
    const remainingLetters = generateRandomStringNoNumber().slice(0, 7).split('')  
    return firstThreeLetters + separator + remainingLetters.join('');  
}  
function generateRandomStringNoNumber() {
  let result = ''
  const characters =
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
  const charactersLength = characters.length
  for (let i = 0; i < 10; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength))
  }
  return result
}  
  
function subDescStr (str) {
  let startIndex = str.indexOf('1）实体定义：') + '1）实体定义：'.length
  let endIndex = str.indexOf('2）业务用途：')
  return str.substring(startIndex, endIndex)
}

// const jsonArray = getJSONoneSheet('数据对应关系')
// const jsonArray = getJSON()
// console.log(jsonArray);
// 输出处理后的数据格式
// const data = {
//   array:jsonArray
// }
// let table = jsonArray.map(item => {
//   item.appName = generateRandomString()
//   return item
// })
// const data = {
//   table: jsonArray.map(item => {
//     item.desc = subDescStr(item.desc)
//     return item
//   }),
// }
// let arr = getArrayJOSN()
// console.log(typeof arr);
// const data = {
//   array: arr.map(item => {
//     item.desc = subDescStr(item.desc)
//     return item
//   })
// }
// console.log(data)
// const data = {
//   table: array,
// }
for (const key in data) {
  if (Object.hasOwnProperty.call(data, key)) {
    data[key].array = array.filter(item => item['标号'] === key)
  }
}

// console.log("数据:",data.table.length);

doc.render(data)
const generatedDocx = doc.getZip().generate({ type: 'nodebuffer' })
fs.writeFileSync('./output/15.2实体合稿.docx', generatedDocx)
